package utils

import (
	"log"
	"os"

	"github.com/joho/godotenv"
)

func LoadEnv() {
	err := godotenv.Load(".env")
	if err != nil {
		log.Println("---failed to load .env config file---")
		log.Println("---loaded default settings---")
	}
	setDefaultEnv()
}

func setDefaultEnv() {
	if _, exists := os.LookupEnv("SS_AllowOrigins"); !exists {
		os.Setenv("SS_AllowOrigins", "*")
	}

	if _, exists := os.LookupEnv("SS_StaticDir"); !exists {
		os.Setenv("SS_StaticDir", "./static")
	}

	if _, exists := os.LookupEnv("SS_TLS"); !exists {
		os.Setenv("SS_TLS", "OFF")
	} else {
		if _, exists := os.LookupEnv("SS_TLS_CERT"); !exists {
			if _, exists := os.LookupEnv("SS_DOMAIN"); !exists {
				log.Panic("SS_DOMAIN is not set")
			}
			if _, exists := os.LookupEnv("SS_CrtDir"); !exists {
				log.Println("SS_CrtDir is not set. Default dir ./certs")
				os.Setenv("SS_CrtDir", "./certs")
			}
		}
	}

	if _, exists := os.LookupEnv("SS_PORT"); !exists {
		os.Setenv("SS_PORT", ":8080")
	}

	log.Printf(`OIO-Static_Server settings:
	 	SS_AllowOrigins = %s
		SS_StaticDir = %s
		SS_PORT = %s
		SS_TLS = %s
	`, os.Getenv("SS_AllowOrigins"), os.Getenv("SS_StaticDir"), os.Getenv("SS_PORT"), os.Getenv("SS_TLS"))
}
